<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <el-tab-pane label="角色管理">
            <el-row style="height:60px">
              <el-button type="primary" size="small" icon="el-icon-plus" @click="showDialog = true">新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles" style="width:100%">
              <el-table-column label="序号" type="index" width="120" :index="indexMethod" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="success" size="small" @click="hAssign(scope.row.id)">分配权限</el-button>
                  <el-button type="primary" size="small" @click="hEdit(scope.row)">编辑</el-button>
                  <el-button type="danger" size="small" @click="hDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex" justify="center" align="middle" style="height:60px">
              <!-- 分页组件 -->
              <el-pagination
                layout="prev, pager, next"
                :total="total"
                :page-size="pageParams.pageSize"
                :current-page.sync="currentPage"
                @current-change="hCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 新增弹框 -->
    <el-dialog
      :title="cTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="close"
    >
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="showDialog= false">取消</el-button>
          <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 角色分配权限 -->
    <el-dialog
      title="分配权限"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogAssign"
      @close="closeDialogAssign"
    >
      <assign-permission v-if="showDialogAssign" ref="tree" :role-id="roleId" @closeTree="closeDialogAssign" />
    </el-dialog>
  </div>
</template>

<script>
import assignPermission from './assignPermission'
import { getRoles, deleteRole, addRole, updateRole } from '@/api/setting'

export default ({
  components: {
    assignPermission
  },

  data() {
    return {
      roleId: '',
      showDialogAssign: false, // 分配权限对话框
      // 默认选中
      currentPage: 0,
      activeName: 'first',
      showDialog: false,
      isEdit: false, // 是否是编辑
      roles: [],
      pageParams: {
        page: 1, // 查询第一页
        pageSize: 2// 每页两条..要与pagination中pagesize一致
      },
      total: 0, // 总的数据条数
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    isLastPage: function() {
      const maxNum = Math.ceil(this.total / this.pageParams.pageSize)
      return this.pageParams.page === maxNum
    },
    // 表格中最大的页码
    maxNum() {
      return Math.ceil(this.total / this.pageParams.pageSize)
    },
    // 最后一页是不是满的
    islastPageFulled: function() {
      return this.total % this.pageParams.pageSize === 0
    },
    cTitle() {
      return this.isEdit ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {

    async loadRoles() {
      try {
        // page, pageSize
        const res = await getRoles(this.pageParams.page, this.pageParams.pageSize)
        console.log(res)
        this.roles = res.data.rows
        this.total = res.data.total
        this.currentPage = this.pageParams.page
      } catch (err) {
        console.log(err)
      }
    },
    // 点击页码的回调，会自动传入当前的页码
    hCurrentChange(curPage) {
      console.log('当前的页码', curPage)
      // 1. 更新页码
      this.pageParams.page = curPage
      // 2. 重发请求
      this.loadRoles()
    },
    async doDel(id) {
      try {
        const res = await deleteRole(id)
        console.log(res)
        // 1. 提示
        this.$message.success('删除成功')
        // 如果当前表格中只有一条伤处之后自动请求上一页数据
        if (this.roles.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        // 2. 重新请求
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    hDel(id) {
      this.$confirm('此操作将永久删除该角色，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 增加
    async doAdd() {
      // this.$refs.roleForm.resetFields()
      try {
        // 调用接口
        const res = await addRole(this.roleForm)
        console.log(res)
        this.$message.success('增加成功')
        this.isEdit = false
        // 关闭弹层
        this.showDialog = false
        // if(表格的最后一项是满){
        //   想查看最新添加的数据，要跳到最大码的下一页
        // }
        if (this.islastPageFulled) {
          this.pageParams.page = this.maxNum + 1
          console.log(this.islastPageFulled + 1)
        } else {
        // 想查看最新添加的数据，跳到最大页码
          this.pageParams.page = this.maxNum
          console.log(this.islastPageFulled)
        }
        // if (this.roles.length === this.pageParams.pageSize) {
        //   this.pageParams.page++
        // }
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message.success('增加失败')
      }
    },
    // 用户点击了保存后
    hSubmit() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 用户点击了编辑
    hEdit(row) {
      // 把当前的数据直接给表单
      // row是一个对象，表示一行数据
      // 赋值是浅拷贝，导致this.roleForm和row指向同一内存空间
      // 解决：变成深拷贝，创建一个全新的对象与row的数据是一样的
      // this.roleForm = row
      // // 显示弹层
      this.showDialog = true
      // this.isEdit = true
      this.roleForm = { ...row }
      // 更新编辑状态
      this.isEdit = true
    },
    // 编辑
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm)
        console.log(res)
        this.showDialog = false
        this.loadRoles()
        this.$message.success('编辑成功')
      } catch (err) {
        console.log(err)
        this.$message.success('编辑失败')
      }
    },
    indexMethod(index) {
      index = (index + 1) + (this.pageParams.page - 1) * this.pageParams.pageSize
      return index
    },
    close() {
      this.$refs.roleForm.resetFields()
      this.isEdit = false
      // bug完成！！
      this.roleForm = {}
    },
    // 显示弹层
    hAssign(id) {
      this.roleId = id
      this.showDialogAssign = true
    },
    closeTree(id) {
      this.roleId = id
      this.showDialogAssign = true
      // 手动调用子组件的loadPermissionByRoleId，去根据最新的roledId获取权限信息
      // this.$nextTick(() => {
      this.$refs.tree.loadPermissionByRoleId()
      // })
    },
    closeDialogAssign() {
      this.showDialogAssign = false
      this.$refs.tree.loadPermissionByRoleId()
    }
  }
})

</script>
